<template>
  <a-modal
    :open="open"
    :width="800"
    title="退费"
    centered
    :closable="false"
    ok-text="确定"
    :ok-button-props="{ disabled: disabledState || !formStatus.balance, loading: loadingState }"
    @ok="onOk"
    @cancel="onCancel"
  >
    <a-form :model="formStatus" class="form-style-flex" :label-col="{ style: { width: '100px' } }">
      <a-form-item label="会员余额" class="w-1/2">
        <div class="text-red-500 font-bold flex items-center text-lg">
          ￥
          <div class="pl-1 text-lg">{{ formatAmount(businessData.rechargeamount) }}</div>
        </div>
      </a-form-item>
      <a-form-item label="赠送金额" class="w-1/2">
        <div class="text-red-500 font-bold flex items-center text-lg">
          ￥
          <div class="pl-1 text-lg">{{ formatAmount(businessData.giveamount) }}</div>
        </div>
      </a-form-item>
      <a-form-item label="退充值金额" class="w-1/2" :rules="[{ required: true, message: '请输入退充值金额' }]">
        <a-input v-model:value="formStatus.balance" v-input:float size="large" placeholder="请输入" @blur="onBlurBalance(1)">
          <template #suffix> <span class="text-gray-400">元</span> </template>
        </a-input>
      </a-form-item>
      <a-form-item label="退赠送金额" class="w-1/2">
        <a-input v-model:value="formStatus.givebalance" v-input:float size="large" placeholder="请输入" @blur="onBlurBalance(2)">
          <template #suffix> <span class="text-gray-400">元</span> </template>
        </a-input>
      </a-form-item>
    </a-form>
    <a-form :model="formState" class="cost-form-style pb-4" :label-col="{ style: { width: '100px' } }">
      <a-divider class="!mb-6 mt-4" />
      <!-- <div class="-my-2 text-red-500">*退费累计金额不可大于应退金额</div> -->
      <div class="flex flex-wrap mt-6">
        <a-form-item v-for="item in chargeTypeList" :key="item.id" :label="item.zffsmc" class="w-1/2">
          <a-input-group class="!flex">
            <a-input
              :key="item.zffsdm"
              v-model:value="formState[item.zffsdm]"
              :disabled="isDisabledAll || (item.zffsdm === 'vipzf' && isDisabledVip)"
              size="large"
              class="-mr-[1px]"
              placeholder="0.00"
              @blur="handlerBlur(item.zffsdm)"
              @change="handlerChangePrice(item.zffsdm)"
            >
              <template #prefix> <span class="text-gray-400">￥</span> </template>
            </a-input>
            <a-button
              :disabled="isDisabledAll || (item.zffsdm === 'vipzf' && isDisabledVip)"
              class="!w-10 !rounded-l-none"
              size="large"
              @click="onclickAllPrice(item)"
            >
              <template #icon><ArrowLeftOutlined class="text-gray-400 text-xs" /></template>
            </a-button>
          </a-input-group>
        </a-form-item>
      </div>
    </a-form>
    <a-form class="pr-7 pl-4 -mt-1">
      <a-form-item label="备注" class="w-full">
        <a-textarea v-model:value="memo" :rows="3" placeholder="请输入" />
      </a-form-item>
    </a-form>
    <a-divider />
  </a-modal>
</template>
<script setup>
import { onMounted, ref, watch } from 'vue'
import { ArrowLeftOutlined } from '@ant-design/icons-vue'
import { omitBy } from 'lodash-es'
import { message } from 'ant-design-vue'
import { formatAmount } from '@/utils/format.js'
import { post } from '@/utils/request'

const emit = defineEmits(['update:open', 'success'])
const props = defineProps({
  open: Boolean,
  type: {
    type: String,
    default: () => 'zf'
  },
  businessData: {
    type: Object,
    default: () => ({})
  },
  chargeTitle: {
    type: String,
    default: () => ''
  },
  loadingState: {
    type: Boolean,
    default: () => false
  }
})

const memo = ref('')
const chargeTypeList = ref([])
const formStatus = ref({})
const formState = ref({})
const paymentAmount = ref({})
// const priceTotal = ref(0)
const disabledState = ref(true)

// 判断退费是否大于应退
const onBlurBalance = (status) => {
  if (status === 1) {
    formStatus.value.balance && (formStatus.value.balance = formatAmount(formStatus.value.balance))
    if (formStatus.value.balance && Number(formStatus.value.balance) > Number(props.businessData.rechargeamount)) {
      formStatus.value.balance = formatAmount(props.businessData.rechargeamount)
      return message.error('不能大于应退充值金额')
    }
  } else {
    formStatus.value.givebalance && (formStatus.value.givebalance = formatAmount(formStatus.value.givebalance))
    if (formStatus.value.givebalance && Number(formStatus.value.givebalance) > Number(props.businessData.giveamount)) {
      formStatus.value.givebalance = formatAmount(props.businessData.giveamount)
      return message.error('不能大于应退赠送金额')
    }
  }
}

// 金额改变
const handlerChangePrice = (zffsdm = '') => {
  // priceTotal.value = 0
  formState.value[zffsdm] = formState.value[zffsdm].replace(/[^\d.]/g, '')
  // for (const key in formState.value) {
  //   if (key !== '') {
  //     priceTotal.value = +formState.value[key] + priceTotal.value
  //   }
  // }
  // if (priceTotal.value > +props.businessData.bcyt_st) {
  //   message.error('退费累计金额不可大于应退金额')
  //   formState.value[zffsdm] = null
  //   return
  // }

  // if (Number(formatAmount(priceTotal.value)) === Number(props.businessData.bcyt_st)) {
  //   disabledState.value = false
  // } else {
  //   disabledState.value = true
  // }
}

// 金额失去焦点
const handlerBlur = (zffsdm = '') => {
  if (formState.value[zffsdm] && formStatus.value.balance) {
    if (Number(formState.value[zffsdm]) > Number(formStatus.value.balance)) {
      formState.value[zffsdm] = formatAmount(formStatus.value.balance)
    }
  }
  if (zffsdm !== '') {
    formState.value[zffsdm] = formState.value[zffsdm] ? formatAmount(formState.value[zffsdm]) : ''
    disabledState.value = !chargeTypeList.value.some((list) => formState.value[list.zffsdm])
  }
}

// 单项全部
const onclickAllPrice = (item) => {
  chargeTypeList.value.forEach((list) => (formState.value[list.zffsdm] = ''))
  formState.value[item.zffsdm] = formatAmount(formStatus.value.balance)
  formState.value[item.zffsdm] && (disabledState.value = false)
  // if (isDisabledVip.value) {
  //   formState.value = {}
  //   formState.value = { [item.zffsdm]: formatAmount(props.businessData.bcyt_st - props.businessData.vipzf), vipzf: formatAmount(props.businessData.vipzf) }
  //   disabledState.value = false
  // } else {
  //   formState.value = {}
  //   formState.value = { [item.zffsdm]: formatAmount(props.businessData.bcyt_st) }
  //   disabledState.value = false
  // }
}

// 重置
const onRest = () => {
  formState.value = {}
  formStatus.value = {}
  // onVipReturn()
  chargeTypeList.value.forEach((item) => {
    paymentAmount.value[item.zffsdm] = 0
  })
}
// 支付方式列表
const getChargeTypeList = async () => {
  const { code, data } = await post('/outp/oupCharge/getChargeTypeList')
  if (code !== 0) return
  data.forEach((item) => {
    paymentAmount.value[item.zffsdm] = 0
  })
  chargeTypeList.value = data
}

// 保存
const onOk = async () => {
  if (formStatus.value.balance && Number(formStatus.value.balance) > Number(props.businessData.rechargeamount)) {
    return message.error('不能大于应退充值金额')
  }
  if (formStatus.value.givebalance && Number(formStatus.value.givebalance) > Number(props.businessData.giveamount)) {
    return message.error('不能大于应退赠送金额')
  }
  Object.keys(formState.value).forEach((i) => {
    Object.keys(paymentAmount.value).forEach((j) => {
      if (i === j) {
        paymentAmount.value[j] = formState.value[i]
      }
    })
  })
  const params = {
    ...paymentAmount.value,
    brId: props.businessData.brId,
    cardId: props.businessData.cardId,
    balance: formStatus.value.balance,
    givebalance: formStatus.value.givebalance || 0,
    ysbalance: props.businessData.rechargeamount,
    ysgivebalance: props.businessData.giveamount,
    ssje: formStatus.value.balance,
    ysje: formStatus.value.balance,
    cardNo: props.businessData.cardNo
  }
  const result = omitBy(params, (val) => val === null)
  const { code, msg } = await post('/outp/oupCharge/doSaveMembercardRefund', result)
  if (code !== 0) return message.error(msg)
  message.success(msg)
  emit('update:open')
  emit('success')
}
const isDisabledAll = ref(false)
const isDisabledVip = ref(false)
// const onVipReturn = () => {
//   if (props.businessData.vipzf === 0 || !props.businessData.vipzf) return
//   if (props.businessData.vipzf > props.businessData.bcyt_st || props.businessData.vipzf === props.businessData.bcyt_st) {
//     formState.value.vipzf = formatAmount(props.businessData.bcyt_st)
//     isDisabledAll.value = true
//     disabledState.value = false
//   } else {
//     formState.value.vipzf = formatAmount(props.businessData.vipzf)
//     isDisabledVip.value = true
//   }
// }
watch(
  () => props.open,
  (val) => {
    if (val) {
      isDisabledVip.value = false
      disabledState.value = true
    }
    onRest()
  },
  { immediate: true }
)

const onCancel = () => {
  emit('update:open', false)
}
onMounted(() => {
  getChargeTypeList()
})
</script>
<style lang="less" scoped>
.cost-form-style {
  .charge-details {
    color: #8e8b8b;
    font-size: 13px;
  }
  :deep(.ant-form-item) {
    padding: 0 3px;

    .ant-form-item-label {
      width: 75px;
      padding-top: 4px;
      label {
        color: #5d5d5d;
        font-size: 16px;
      }
    }
    .ant-form-item-control {
      flex: none;
      width: 240px;
      color: #2b2b2b;
      font-size: 15px;
      text-align: right;
      .ant-input {
        text-align: right;
      }
    }
  }
}
.in-title {
  color: #a4adb3;
}
</style>
